//
//  SEGYellowPageController.m
//  ExcellentHome
//
//  Created by 陈区 on 14-1-4.
//  Copyright (c) 2014年 陈区. All rights reserved.
//

#import "SEGYellowPagesTypeViewController.h"
#import "YellowPagesModel.h"

#import "SEGYellowPageController.h"

#import "SEGYellowPageViewModel.h"

@interface SEGYellowPageController ()<SEGNewAlertViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, copy)  NSString *callString;
/// tableView
@property (nonatomic, strong) UITableView *tableView;
/// viewModel
@property (nonatomic, strong) SEGYellowPageViewModel *viewModel;

@end

@implementation SEGYellowPageController
 
static SEGYellowPageController *sharedViewCtl = nil;
+ (SEGYellowPageController *)sharedViewController {
    if(!sharedViewCtl) {
        sharedViewCtl = [[SEGYellowPageController alloc] init];
        sharedViewCtl.hidesBottomBarWhenPushed = YES;
    }
    return sharedViewCtl;
}
+ (void)destroySharedViewController {
    sharedViewCtl = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.title.length>0?self.title:@"黄页";
    [self showCustomNavigationBackButton];
    [self.view addSubview:self.tableView];
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    @weakify(self);
    [self.viewModel.signal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        // 防止self释放
        if (!self) {
            return;
        }
        self.tableView.backgroundColor = self.viewModel.allArray.count > 0 ? kColor_bg:UIColor.clearColor;
        // 36283 【深到家v1.2.0】iOS 便民列表有数据是，界面展示错误
        if (self.viewModel.allArray.count == 0) {
            NSDictionary *params =@{@"view":self.view};
            [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:params];
        }
        else {
            [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":self.view}];
        }
        [self.tableView reloadData];
    }];
}

#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.viewModel.normalArray.count > 0) {
        return 2;
    } else if (self.viewModel.allArray.count > 0) {
        return 1;
    } else {
        return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(self.viewModel.normalArray.count > 0) {
        if (section == 0) return 40;
        return 60;
     } else if (self.viewModel.allArray.count > 0) {
        return 40;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView*headerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    headerView.backgroundColor = [UIColor clearColor];
    
    CGRect cellBounds = CGRectMake(0, 40, CGRectGetWidth(self.view.bounds), 0.5);
    UIImageView *linebg = [[UIImageView alloc] initWithFrame:cellBounds];
    linebg.image = [UIImage imageWithContentsOfFile:SEGPicName(@"common_line610px")];
    [headerView addSubview:linebg];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 40)];
    title.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
    title.backgroundColor=kColor_W;
    title.textColor = kColor_T;
    [headerView addSubview:title];
    if (self.viewModel.normalArray.count > 0) {
        switch (section) {
            case 0:{
                title.text = @"     常用";
                headerView.backgroundColor = kColor_W;
                break;
            }
            case 1:{
                title.text = @"     全部";
                title.frame=CGRectMake(0, 20, CGRectGetWidth(self.view.bounds), 40);
                linebg.frame=CGRectMake(0, 60, CGRectGetWidth(self.view.bounds), 0.5);
                CGRect cellBounds = CGRectMake(0, 20, CGRectGetWidth(self.view.bounds), 0.5);
                UIImageView *linebg = [[UIImageView alloc] initWithFrame:cellBounds];
                linebg.image = [UIImage imageWithContentsOfFile:SEGPicName(@"common_line610px")];
                [headerView addSubview:linebg];
                break;
            }
                
            default:
                break;
        }
    } else if (self.viewModel.allArray.count > 0) {
        title.text = @"     全部";
        headerView.backgroundColor = kColor_W;
    }
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.viewModel.normalArray.count > 0) {
        if (section == 0) return self.viewModel.normalArray.count;
        return self.viewModel.allArray.count;
    } else if (self.viewModel.allArray.count > 0) {
        return self.viewModel.allArray.count;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdStr = @"CellReuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdStr];
    if(!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdStr];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        CGRect cellBounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 0.5);
        UIImageView *linebg = [[UIImageView alloc] initWithFrame:cellBounds];
        linebg.tag=100;
        linebg.image = [UIImage imageWithContentsOfFile:SEGPicName(@"common_line610px")];
        [cell.contentView addSubview:linebg];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0,210, 44)];
        titleLabel.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        titleLabel.textColor=kColor_2;
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.tag = 101;
        [cell.contentView addSubview:titleLabel];
        UIImage *image = [[UIImage imageWithContentsOfFile:SEGPicName(@"home_numberbook_btn_green")] imageByTintColor:kColor_T];
        CustomButtonView *btnStop = [CustomButtonView buttonWithType:UIButtonTypeCustom];
        btnStop.userInteractionEnabled = NO;
        btnStop.tag = 102;
        btnStop.frame = CGRectMake(CGRectGetWidth(self.view.bounds)-20 - 25,8.5,25,25);
        [btnStop setTitleColor:kColor_W forState:UIControlStateNormal];
        btnStop.titleLabel.font = [UIFont systemFontOfSize:12];
        [btnStop setBackgroundImage:image forState:UIControlStateNormal];
        [cell.contentView addSubview:btnStop];

        UIImageView *arrow = [[UIImageView alloc] init];
        arrow.image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_more_gray")];
        arrow.tag=103;
        arrow.hidden=YES;
        arrow.frame=CGRectMake(CGRectGetWidth(self.view.bounds)-arrow.image.size.width-20, (44-arrow.image.size.height)/2, arrow.image.size.width, arrow.image.size.height);
        [cell.contentView addSubview:arrow];
   
    }
    UIImageView * line = (UIImageView *)[cell viewWithTag:100];
    UILabel * title = (UILabel *)[cell viewWithTag:101];
    CustomButtonView *btnStopTap=(CustomButtonView *)[cell viewWithTag:102];
    UIImageView *arrow=(UIImageView *)[cell viewWithTag:103];
    
    if (self.viewModel.normalArray.count > 0){
        if (indexPath.section == 0) {
            YellowPagesModel *entity = [self.viewModel.normalArray objectAtIndex:indexPath.row];
            title.text =  entity.name;
            btnStopTap.hidden=NO;
            arrow.hidden=YES;
            if (indexPath.row==[self.viewModel.normalArray count]-1) {
                line.frame=CGRectMake(0, 43.5, CGRectGetWidth(self.view.bounds), 0.5);
            }else{
                line.frame=CGRectMake(0, 43, CGRectGetWidth(self.view.bounds), 0.5);
            }

        } else {
            btnStopTap.hidden=YES;
            arrow.hidden=NO;

            title.text=[NSString stringWithFormat:@"%@",[self.viewModel.allArray objectAtIndex:indexPath.row]];
            
            if (indexPath.row==[self.viewModel.allArray count]-1) {
                line.frame=CGRectMake(0, 43.5, CGRectGetWidth(self.view.bounds), 0.5);
            }else{
                line.frame=CGRectMake(0, 43, CGRectGetWidth(self.view.bounds), 0.5);
            }

        }
    } else if (self.viewModel.allArray.count > 0) {
        btnStopTap.hidden = YES;
        arrow.hidden = NO;

        title.text = [NSString stringWithFormat:@"%@",[self.viewModel.allArray objectAtIndex:indexPath.row]];
        
        if (indexPath.row == [self.viewModel.allArray count]-1) {
            line.frame=CGRectMake(0, 43.5, CGRectGetWidth(self.view.bounds), 0.5);
        } else {
            line.frame=CGRectMake(0, 43, CGRectGetWidth(self.view.bounds), 0.5);
        }

    }
    
    return cell;
}
#pragma mark -Tableview delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.viewModel.normalArray.count > 0){
        if (indexPath.section == 0) {
            YellowPagesModel *entity = [self.viewModel.normalArray objectAtIndex:indexPath.row];
            [self showCallAlertWithCallString:entity.tel];
            return;
        }
        if (indexPath.section == 1) {
            SEGYellowPagesTypeViewController *typeView = [[SEGYellowPagesTypeViewController alloc] init];
            typeView.title = [self.viewModel.allArray objectAtIndex:indexPath.row];
            typeView.typeAry = [self.viewModel.yellowPagesManager.dataSourceAllArray objectAtIndex:indexPath.row];
            typeView.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:typeView animated:YES];
        }
    } else {
        SEGYellowPagesTypeViewController *typeView = [[SEGYellowPagesTypeViewController alloc] init];
        typeView.title = [self.viewModel.allArray objectAtIndex:indexPath.row];
        typeView.typeAry = [self.viewModel.yellowPagesManager.dataSourceAllArray objectAtIndex:indexPath.row];
        typeView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:typeView animated:YES];
    }
}

#pragma mark - SEGNewAlertView
- (void)showCallAlertWithCallString:(NSString *)callString {
    self.callString = callString;
    SEGNewAlertView *alertView = [[SEGNewAlertView alloc] init];
    alertView.dismissWhenTouch = YES;
    [alertView showWithAlertText:[NSString stringWithFormat:@"%@",self.callString] delegate:self buttonTitlesArray:@[@"取消",@"呼叫"]];
}
#pragma mark - SEGNewAlertViewDelegate
- (void)segNewAlertView:(UIView *_Nullable)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        if (@available(iOS 8.0, *)) {
            NSString *str = [NSString stringWithFormat:@"telprompt://%@",self.callString];
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
            }
        }
    }
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        CGRect appbounds = CGRectMake(0,0, LYScreenWidth(), LYScreenHeight()-kNavigationBarAndStatusBarHeight);
        _tableView = [[UITableView alloc] initWithFrame:appbounds style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundView = nil;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}
- (SEGYellowPageViewModel *)viewModel {
    if (!_viewModel) _viewModel = [[SEGYellowPageViewModel alloc] init];
    return _viewModel;
}

@end
